package com.mr.qa;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.hibernate.Transaction;

import com.mr.qa.action.MoneyAction;
import com.mr.qa.bo.Message;
import com.mr.qa.bo.MoneyReport;
import com.mr.qa.bo.User;
import com.mr.qa.dao.impl.MessageDAO;
import com.mr.qa.dao.impl.UserDAO;
import com.mr.qa.util.DateUtil;
import com.mr.qa.util.HibernateSessionFactory;


public class BatchClass {
	
	static String propFile = "Award.properties";
	static String strDateFrom;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		
		getProperties();
		
		Date fromDate = DateUtil.StringToDate(strDateFrom, "yyyy-MM-dd");
		
		Calendar calNow = Calendar.getInstance();
		Calendar calWeekAgo = Calendar.getInstance();
		calNow.setTime(fromDate);
		calWeekAgo.setTime(fromDate);
		
		Date dateNow = new Date();
		String strDateNow = DateUtil.dateToString(dateNow, "yyyy-MM-dd HH:mm:ss");
		
		calNow.add(Calendar.DATE, -1);
		calWeekAgo.add(Calendar.DATE, -7);
		
		Date datePre = calNow.getTime();
		Date dateWeekAgo = calWeekAgo.getTime();
		
		String strNow = DateUtil.dateToString(datePre, "yyyy-MM-dd");
		String strWeekAgo = DateUtil.dateToString(dateWeekAgo, "yyyy-MM-dd");
		System.out.println(strNow);
		System.out.println(strWeekAgo);
		
		Transaction tx = null;
		try{
			
			MoneyAction moneyAction = new MoneyAction();
			List list = moneyAction.countReport(GlobalConfigs.MONEY_AWARD_LOGIN_ID, strWeekAgo, strNow);
			tx = HibernateSessionFactory.getSession().beginTransaction();
			//MessageAction msgAction = new MessageAction();
			MessageDAO messageDAO = new MessageDAO();
			
			File file = new File("awardLog.txt");
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			UserDAO userDAO = new UserDAO();
			User mainUser = (User)userDAO.findByLoginName("Mainframer ").get(0);
			
			bw.write("From Date: " + strNow);
			bw.newLine();
			bw.write("To Date: " + strWeekAgo);
			bw.newLine();
			
			
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				MoneyReport moneyReport = (MoneyReport) iterator.next();
				User user = userDAO.findById(moneyReport.getUserId());
				System.out.println(user.getLoginName() + moneyReport.getTotalScore());
				if(moneyReport.getTotalScore() >= GlobalConfigs.WEEKLY_AUTO_AWARD_CRITERIA){
					userDAO.spendMoney(user, 0, "��̳��Ծ�Ȼ�ֽ���", "autoWeeklyAward", "2", moneyReport.getTotalScore());
					Message msg = new Message();
					msg.sendMessage("��ֽ���֪ͨ", "������̳��Ծ�Ȼ�ֽ���" + moneyReport.getTotalScore() + "��",
							dateNow, mainUser, user, messageDAO);
					bw.write("user: " + user.getLoginName() + " is awarded with " + moneyReport.getTotalScore() + " on " + strDateNow );
					bw.newLine();
					
				}
			}
			bw.close();
			fw.close();
			calNow.add(Calendar.DATE, 8);
			fromDate = calNow.getTime();
			
			strDateFrom = DateUtil.dateToString(fromDate, "yyyy-MM-dd");
			setProperties();
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			StackTraceElement[] st = e.getStackTrace();
			File file = new File("awardError.txt");
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			StringBuffer error = new StringBuffer();
			for (int i = 0; i < st.length; i++) {
				error.append(st[i].toString());
			}
			fw.write(error.toString());
			bw.close();
			fw.close();
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public static void getProperties() throws Exception{
		InputStream is = null;
		try {
			//is = this.getClass().getClassLoader().getResourceAsStream(GlobalConfigs.SYSTEM_PROPERTY_FILE);
			String filePath = BatchClass.class.getResource("/").getPath() + propFile;
			filePath = URLDecoder.decode(filePath, "UTF-8");
			//filePath = filePath.replaceAll("%20", " ");
			is = new FileInputStream(filePath);
			Properties props = new Properties();
			props.load(is);
			BatchClass.strDateFrom = props.getProperty("fromDate");
		} catch (IOException e) {
			throw e;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ex) {
					throw ex;
				}
			}
		}
	}
	
	public static void setProperties() throws Exception {
		try {
			String filePath = BatchClass.class.getResource("/").getPath() + propFile;
			
			filePath = URLDecoder.decode(filePath, "UTF-8");
			// filePath = filePath.replaceAll("%20", " ");
			Properties props = new Properties();
			InputStream is = null;
			is = new FileInputStream(filePath);
			props.load(is);
			is.close();
			props.setProperty("fromDate", strDateFrom);
			OutputStream ops = new FileOutputStream(filePath);
			props.store(ops, "System Parameter");
			ops.close();
		} catch (IOException e) {
			throw e;
		}
	}

}
